//
//  ZBXMTitleView.swift
//  zhiboxiangmu
//
//  Created by 丁鼎 on 2017/7/4.
//  Copyright © 2017年 丁鼎. All rights reserved.
//

import UIKit

protocol ZBXMTitleViewDelegate : class {
    
    func titleView(_ titleView : ZBXMTitleView , targetIndex:Int)
    
}
class ZBXMTitleView: UIView {

    weak var delegate : ZBXMTitleViewDelegate?
    
    fileprivate var titles:[String]
    fileprivate var style :ZBXMPageStyle
    fileprivate var titleLabels : [UILabel] = [UILabel]()
    fileprivate lazy var normalColor : (CGFloat , CGFloat, CGFloat) = self.style.titleNormalColor.getRGBValue()
    fileprivate lazy var selectColor : (CGFloat , CGFloat, CGFloat) = self.style.titleSelectColor.getRGBValue()
    fileprivate lazy var deltaColor : (CGFloat ,CGFloat ,CGFloat) = {
        let deltaR = self.selectColor.0 - self.normalColor.0
        let deltaG = self.selectColor.1 - self.normalColor.1
        let deltaB = self.selectColor.2 - self.normalColor.2
        
        return (deltaR,deltaG,deltaB)
 
    }()

    fileprivate lazy var bottomLine : UIView = {
        var bottomview = UIView()
        bottomview.backgroundColor = self.style.bottomLineColor
        return bottomview;
        
    }()
    
    fileprivate lazy var coverView : UIView = {
       var coverview = UIView()
        coverview.backgroundColor = UIColor.black
        coverview.alpha = self.style.coverViewAlpha
        return  coverview
    }()
    
    fileprivate lazy var scrollview : UIScrollView = {
       let scrolleview = UIScrollView(frame:self.bounds)
        scrolleview.scrollsToTop = true
        scrolleview.showsHorizontalScrollIndicator = false
        scrolleview.showsVerticalScrollIndicator = false
        return scrolleview
    }()
    
    fileprivate var currentIndex : Int = 0
    
    init(frame: CGRect,titles:[String],style:ZBXMPageStyle) {
        self.titles = titles;
        self.style = style
        super .init(frame: frame)
        setupUI()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}


extension ZBXMTitleView{
    
    fileprivate func setupUI(){
        
        //1,加入scrollview
        addSubview(scrollview)
        
        //2,添加title
        setupTitleLabel()
        
        //3,添加title下面的横线
        if style.isBottomLineShow {
        setupBottomLine()
        }
        
        //4,是否显示遮盖
        if style.isCoverViewShow{
        setupCoverView()
        }
        
    }
    
    private func  setupCoverView(){
        scrollview.addSubview(coverView)
        
        guard let firstLabel = titleLabels.first else { return }
        
        let coverW : CGFloat = firstLabel.frame.width + style.coverViewMargin * 2
        let coverH : CGFloat = style.coverViewHeight
        let coverX : CGFloat = firstLabel.frame.origin.x - style.coverViewMargin
        let coverY : CGFloat = (firstLabel.frame.height - coverH) * 0.5
        
        
        coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH)
        coverView.layer.cornerRadius = style.coverViewRadiu
        coverView.layer.masksToBounds = true
        
    }
    
    private func setupBottomLine(){
        scrollview.addSubview(bottomLine)
        bottomLine.frame = titleLabels.first!.frame
        bottomLine.frame.size.height = style.bottomLineHeight
        bottomLine.frame.origin.y = style.titleHeight - style.bottomLineHeight
    }
    
    private func setupTitleLabel(){
        
        for(i,title) in titles.enumerated(){
            //1,创建这些label
            let label = UILabel()
            
            //2,设置属性
            label.text = title
            label.tag = i
            label.textColor = i == 0 ? style.titleSelectColor  : style.titleNormalColor
            label.font = style.titleDefaultFont
            label.textAlignment = .center
            
            //3,添加进空间
            scrollview.addSubview(label)
            
            //4,添加手势
            let tap = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(tapGaps:)))
            label.isUserInteractionEnabled = true
            label.addGestureRecognizer(tap)
            
            //5,将他们添加到数组中去
            titleLabels.append(label)
        }

        //2,设置Label的frame
        for (i, titleLabel) in titleLabels.enumerated()
        {
            var LabelX : CGFloat = 0
            var LabelW : CGFloat = 0
            let LabelH : CGFloat = style.titleHeight
            let LabelY : CGFloat = 0
            
            
            if style.isScrollEnable {//可以滚动
               LabelW = (titleLabel.text! as NSString) .boundingRect(with: CGSize(width:CGFloat(MAXFLOAT) , height:0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : style.titleDefaultFont], context: nil).width
                LabelX = i == 0 ? style.titleMargin * 0.5 : (titleLabels[i-1].frame.maxX +  style.titleMargin)
                
                
            }else{//不可以滚动
                
                LabelW = bounds.width / CGFloat(titles.count)
                LabelX = LabelW * CGFloat(i)
                
            }
            titleLabel.frame = CGRect(x: LabelX, y: LabelY, width: LabelW, height: LabelH)
            
            if style.isScrollEnable{
                scrollview.contentSize = CGSize(width: titleLabel.frame.maxX, height: 0)
            }

        }
        
        if style.isSclae
        {
        
        titleLabels.first?.transform = CGAffineTransform(scaleX: style.maxScale, y: style.maxScale)
        }
    }

}


//监听手势
extension ZBXMTitleView {
    
    func titleLabelClick(tapGaps :UITapGestureRecognizer){
        
        
        
        
        //0,先判断Label里面有没有值
        guard let selectedLabel = tapGaps.view as? UILabel else {
            return
        }
        
        //1,如果就是这个label就没有必要走下面的方法了
        guard selectedLabel.tag != currentIndex else {
            return
        }
        
        //2,判断是哪一个Label
        let sourceLabel = titleLabels[currentIndex]
        sourceLabel.textColor = style.titleNormalColor
        selectedLabel.textColor = style.titleSelectColor
        currentIndex = selectedLabel.tag
        
        //3,让那个label滚动到中间的位置
       adjustPosition()
        
        //4,通知代理
        if let  delegate = delegate{
            delegate.titleView(self, targetIndex: currentIndex)
        }
        
        //5,调整bottomline位置
        if style.isBottomLineShow {
            UIView.animate(withDuration: 0.25, animations: {
                self.bottomLine.frame.origin.x = selectedLabel.frame.origin.x
                self.bottomLine.frame.size.width = selectedLabel.frame.size.width
            })
        }
        
        if style.isSclae{
            UIView.animate(withDuration: 0.25, animations: {
                sourceLabel.transform = CGAffineTransform.identity
                selectedLabel.transform = CGAffineTransform(scaleX:self.style.maxScale, y:self.style.maxScale)
            })
        }
        
        if style.isCoverViewShow{
            self.coverView.frame.origin.x = style.isScrollEnable ? (selectedLabel.frame.origin.x - style.coverViewMargin) : selectedLabel.frame.origin.x
            self.coverView.frame.size.width = style.isScrollEnable ? (selectedLabel.frame.size.width + 2 * style.coverViewMargin) : selectedLabel.frame.size.width

        }
        
        
    }
    
    fileprivate func adjustPosition(){
        
        let selectedLabel = titleLabels[currentIndex]
        
        var offsetX = selectedLabel.center.x - scrollview.bounds.width * 0.5
        
        if offsetX<0
        {
            offsetX = 0
        }
        
        if offsetX > scrollview.contentSize.width - scrollview.bounds.width
        {
            offsetX = scrollview.contentSize.width - scrollview.bounds.width
        }
        
        scrollview .setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
    }
 
}

//遵守ZBXMContainViewdelegate协议
extension ZBXMTitleView : ZBXMContentViewdelegate
{
    func contentView(_ contentView: ZBXMContentView, didEndScrollew index: Int) {
        currentIndex = index
        adjustPosition()
    }



    
    func contentView(_ contentView: ZBXMContentView, startIndex: Int, targetIndex: Int, progress: CGFloat) {
//        1,根据两个index获取label
        let sourceLabel = titleLabels[startIndex]
        let targetLabel = titleLabels[targetIndex]
//        2,颜色渐变
       
        sourceLabel.textColor = UIColor(r: selectColor.0 - deltaColor.0 * progress, g: selectColor.1 - deltaColor.1 * progress, b: selectColor.2 - deltaColor.2 * progress)
        targetLabel.textColor = UIColor(r: normalColor.0 + deltaColor.0 * progress, g: normalColor.1 + deltaColor.1 * progress, b: normalColor.2 + deltaColor.2 * progress)

        let deltaWidth = targetLabel.frame.size.width -  sourceLabel.frame.size.width
        let deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
        if style.isBottomLineShow
        {
            bottomLine.frame.size.width = progress * deltaWidth + sourceLabel.frame.size.width
            bottomLine.frame.origin.x = progress * deltaX + sourceLabel.frame.origin.x

        }
        
        let deltaScale = style.maxScale - 1.0

        
        if style.isSclae{
            sourceLabel.transform = CGAffineTransform(scaleX: style.maxScale - deltaScale * progress, y: style.maxScale - deltaScale * progress)
            targetLabel.transform = CGAffineTransform(scaleX: 1.0 + deltaScale * progress, y: 1.0 + deltaScale * progress)
            
        }
        
        if style.isCoverViewShow{
            
            coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverViewMargin + deltaX * progress) :  (sourceLabel.frame.origin.x +  deltaX * progress)
            coverView.frame.size.width  = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverViewMargin + deltaWidth * progress) : (sourceLabel.frame.width + deltaWidth * progress)
  
        }
        

    }

}
